package com.example.accountingapp;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 添加或者修改
 */
public class AddNotepadActivity extends AppCompatActivity {
    MySqliteOpenHelper helper = null;
    private EditText etTitle;
    private EditText etContent;
    private Notepad notepad;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nodepad_add);
        etTitle = findViewById(R.id.title);
        etContent = findViewById(R.id.content);
        helper = new MySqliteOpenHelper(this);
        notepad = (Notepad) getIntent().getSerializableExtra("notepad");
        if (notepad != null) {
            etTitle.setText(notepad.getTitle());
            etContent.setText(notepad.getContent());
        }
    }

    /**
     * 保存
     *
     * @param view
     */
    public void save(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        String title = etTitle.getText().toString();
        String content = etContent.getText().toString();
        if ("".equals(title)) {
            Toast.makeText(AddNotepadActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(content)) {
            Toast.makeText(AddNotepadActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (notepad == null) {//新增
            String sql = "insert into notepad(title, content,date) values(?,?,?)";
            db.execSQL(sql, new Object[]{ title, content, sf.format(new Date())});
            Toast.makeText(AddNotepadActivity.this, "新增成功", Toast.LENGTH_SHORT).show();
        } else {//修改
            db.execSQL("update notepad set title = ?, content = ? where id=?", new Object[]{ title, content, notepad.getId()});
            Toast.makeText(AddNotepadActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
        }
        db.close();
        finish();
    }


    //返回
    public void back(View view) {
        finish();
    }
}
